package com.ruoyi.web.controller.supercells;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.page.TableDataList;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.SysNotice;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PathFile;
import com.ruoyi.system.service.IPathFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.config.RuoYiConfig;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 文件路径信息Controller
 * 
 * @author ruoyi
 * @date 2024-04-22
 */
@RestController
@RequestMapping("/system/file")
public class PathFileController extends BaseController
{
    @Autowired
    private IPathFileService pathFileService;

    /**
     * 查询文件路径信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(PathFile pathFile)
    {
        startPage();
        List<PathFile> list = pathFileService.selectPathFileList(pathFile);
        return getDataTable(list);
    }
    /**
     * gaohong 图片接口
     */
    @Anonymous
    @GetMapping("/object")
    public TableDataList objectlist(PathFile pathFile)
    {
        startPage();
        List<PathFile> list = pathFileService.selectPathFileList(pathFile);
        return getDataList(list);
    }
    /**
     * 导出文件路径信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:export')")
    @Log(title = "文件路径信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PathFile pathFile)
    {
        List<PathFile> list = pathFileService.selectPathFileList(pathFile);
        ExcelUtil<PathFile> util = new ExcelUtil<PathFile>(PathFile.class);
        util.exportExcel(response, list, "文件路径信息数据");
    }

    /**
     * 获取文件路径信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId)
    {
        return success(pathFileService.selectPathFileByFileId(fileId));
    }

    /**
     * 新增文件路径信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @Log(title = "文件路径信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PathFile pathFile)
    {
        return toAjax(pathFileService.insertPathFile(pathFile));
    }

    /**
     * 修改文件路径信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "文件路径信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PathFile pathFile)
    {
        return toAjax(pathFileService.updatePathFile(pathFile));
    }

    /**
     * 删除文件路径信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "文件路径信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fileIds}")
    public AjaxResult remove(@PathVariable Long[] fileIds)
    {
        return toAjax(pathFileService.deletePathFileByFileIds(fileIds));
    }


    @PostMapping("/spic")
    public String uploadFile(@RequestParam("picture")MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空！");
        }
        // 上传文件并获取文件保存的路径
        String filePath = FileUploadUtils.upload(RuoYiConfig.getImportPath(), file);
        System.out.println(filePath+"文件路径xxxxxxx");
        // 返回上传的附件在服务器上的保存路径
        // 获取服务器的请求地址
        HttpServletRequest request = ServletUtils.getRequest();
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + filePath;
        System.out.println("文件的 URL 是：" + url);
        return url;
    }

    public String uploadFiles(List<MultipartFile> files) throws Exception {
        // 获取所有的上传文件
        List<MultipartFile> fileList = files;

        if (fileList.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空！");
        }
        // 创建一个用于保存所有文件 URL 地址的数组
        List<String> filePaths = new ArrayList<>();
        // 遍历所有文件，上传并获取文件保存的路径
        for (int i = 0; i < fileList.size(); i++) {
            MultipartFile file = fileList.get(i);
            if (file.isEmpty()) {
                throw new IllegalArgumentException("上传文件不能为空！");
            }
            // 修改为获取对应的键名进行文件上传
            String filePath = FileUploadUtils.upload(RuoYiConfig.getImportPath(), file);
            System.out.println(filePath + " 文件路径");
            // 获取服务器的请求地址（修改此处）
            String url = ServletUtils.getRequest().getScheme() + ":/"+"/" + ServletUtils.getRequest().getServerName() + ":" + ServletUtils.getRequest().getServerPort() + filePath;
            System.out.println("第 " + i + " 个文件的 URL 是：" + url);
            // 将文件的 URL 地址保存到数组中
            filePaths.add(url);
        }
        // 直接返回包含多个 URL 的字符串
        return String.join(",", filePaths);
    }
}
